from flask import Blueprint, render_template, jsonify, request
from models.entity.patrol_manage import PatrolManage
from models.entity.device_type import DeviceType
from models.entity.device import Device
from  models.entity.patrol_recoder import PatrolRecoder
import json
from utils.result import result


mod = Blueprint("core_partrol", __name__, url_prefix="/core/patrol_manage", template_folder="templates",
                static_folder="static")


@mod.route('/add/',methods=['GET','POST'])
def add_patrol_manage():
    """增加设备分类巡检项"""
    """
   {

    "name":"dd5",
    "code":"2dddd",
    "description":"22222"
    }
    """
    try:
        receive = request.data.decode("utf-8")
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    dict = json.loads(receive)
    if "id" in dict:
        dict.pop("id")
    if "code" not in dict:
        return result(success=0, error_code=-1, error_msg="编号不能为空")
    if "content" not in dict:
        return result(success=0, error_code=-1, error_msg="巡检项内容不能为空")
    if PatrolManage.query.filter_by(code=dict["code"]).first() is not None:
        return result(success=0, error_code=-1, error_msg="巡检项编号已存在")
    if not DeviceType.get_device_type_by_id(dict["device_type_id"]):
        return result(success=0, error_code=-1, error_msg="巡检设备类型不存在")
    if PatrolManage.query.filter_by(device_type_id=dict["device_type_id"]).filter_by(content=dict["content"]).first():
        return result(success=0, error_code=-1, error_msg="该巡检项已经存在，不用重复添加")
    patrol_manage = PatrolManage()
    try:
        patrol_manage.from_dict(dict)
    except RuntimeError as e:
        return result(success=0, error_code=-1, error_msg=str(e))
    if patrol_manage.save():
        return result(success=1)
    else:
        return result(success=0, error_code=-3, error_msg="未知错误")


@mod.route('/edit/', methods=['GET', 'POST'])  # 编辑对应的巡检项
def edit_partrol_manage():
    """编辑设备分类巡检"""
    """
    {
    "id":1,
    "name":"0",
    "code":"25"
    }
    """
    try:
        dict = json.loads(request.data.decode("utf-8"))
        print('dict', dict)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")

    patrol_manage = PatrolManage().get_entity_by_id(dict['id'])
    if dict["code"] != patrol_manage.code and PatrolManage().get_patrol_manage_by_code(dict["code"]):
        return result(success=0, error_code=-2, error_msg="编码已经存在，请重新设置")
    if dict["content"] != patrol_manage.content and PatrolManage().query.filter_by(device_type_id=patrol_manage.device_type_id).filter_by(content=dict["content"]).first():
        return result(success=0, error_code=-2, error_msg="巡检项已经存在，不可重复添加")
    try:
        patrol_manage.from_dict(dict)
    except RuntimeError as e:
        return result(success=0, error_code=-2, error_msg=str(e))
    if patrol_manage.save():
        return result(success=1)
    else:
        return result(success=0, error_code=-3, error_msg="未知错误")


@mod.route('/del/', methods=['GET', 'POST'])
def del_patrol_manage():
    """删除对应的巡检项"""
    """
    {
    "id":1
    }

    """
    receive = request.data.decode("utf-8")
    try:
        dict = json.loads(receive)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    patrol_manage = PatrolManage().get_entity_by_id(dict["id"])
    if not patrol_manage:
        return result(success=0, error_code=-1, error_msg="该巡检项不存在")
    # 解除巡检项记录与巡检项的关系
    patrol_recorders = PatrolRecoder().query.filter_by(patrol_manage_id=dict["id"]).all()
    if len(patrol_recorders) != 0:
        for recorder in patrol_recorders:
            recorder.patrol_manage_id = None
            recorder.save()
    if patrol_manage.delete():
        return result(success=1)
    else:
        return result(success=0, error_code=-3, error_msg="未知错误")


@mod.route('/get_all/', methods=['GET', 'POST'])
def get_patrol_manage():
    """得到全部巡检项"""
    t_list = [item.to_dict() for item in PatrolManage().get_list_all()]
    return result(success=1, data=t_list)

@mod.route('/get_all_by_device_type/', methods=['GET', 'POST'])
def get_patrol_manage_all_by_device_type():
    """得到某个设备类型下的巡检项"""
    receive = request.data.decode("utf-8")
    try:
        dict = json.loads(receive)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    patrol_manages = PatrolManage.get_patrol_manage_all_by_device_type(dict["id"])
    t_list = []
    for item in patrol_manages:
        t_list.append(item.to_dict())
    return result(success=1, data=t_list)

@mod.route('/get_valid_by_device_type/', methods=['GET', 'POST'])
def get_patrol_manage_by_device_type():
    """得到某个设备类型下的巡检项"""
    receive = request.data.decode("utf-8")
    try:
        dict = json.loads(receive)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    patrol_manages = PatrolManage.get_patrol_manage_by_device_type(dict['id'])
    t_list = [item.to_dict() for item in patrol_manages]
    return result(success=1, data=t_list)

@mod.route('/get_manage_by_device/', methods=['GET', 'POST'])
def get_patrol_manage_by_device():
    """通过设备得到对应的巡检项"""
    receive = request.data.decode("utf-8")
    try:
        dict = json.loads(receive)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    device = Device.get_device_by_id(dict["id"])
    device_type = device.device_type_id
    patrol_manages = PatrolManage.get_patrol_manage_by_device_type(device_type)
    t_list = []
    for item in patrol_manages:
        t_list.append(item.to_dict())
    return result(success=1, data=t_list)


#  我加的搜索方法
@mod.route("/search/",methods=["POST"])
def patrol_search():
    """
    模糊搜索接口
    """
    # request: json
    # {
    #       "query_word":"query_word"
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    if "query_word" in data:
        query_word=data["query_word"]
    else:
        return result(success=0, error_code=-2, error_msg="数据不完整")
    rdic=PatrolManage.search(query_word)
    return jsonify(rdic)